package com.xm;

import java.io.File;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import com.xm.common.utils.JsonUtils;
import com.xm.config.ResourceConfig;
import com.xm.pojo.Bgm;
import com.xm.service.BgmService;
import enums.BGMOperatorType;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class ZKCuratorClient {

	@Autowired
	ResourceConfig resourceConfig;
	// zk客户端
	private CuratorFramework client = null;	
	final static Logger log = LoggerFactory.getLogger(ZKCuratorClient.class);

	@Autowired
	private BgmService bgmService;
	
	public static final String ZOOKEEPER_SERVER = "39.103.155.210:2181";

	
	public void init() {
		
		if (client != null) {
			return;
		}
		
		// 重试策略
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
		// 创建zk客户端
		client = CuratorFrameworkFactory.builder().connectString(resourceConfig.getZookeeperServer())
				.sessionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("admin").build();
		// 启动客户端
		client.start();
		
		try {
//			String testNodeData = new String(client.getData().forPath("/bgm/22042080T12X8YCH"));
//			log.info("测试的节点数据为： {}", testNodeData);
			addChildWatch("/bgm");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public void addChildWatch(String nodePath) throws Exception{
		final PathChildrenCache cache = new PathChildrenCache(client,nodePath,true);
		cache.start();
		cache.getListenable().addListener(new PathChildrenCacheListener() {
			@Override
			public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
				if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)) {
					log.info("监听到事件 CHILD_ADDED");

					// 1. 从zk获取删除或新增操作和对象信息
					String path = event.getData().getPath();
					String operatorObjStr = new String(event.getData().getData(), "UTF-8");
					Map<String, String> map = JsonUtils.jsonToPojo(operatorObjStr, Map.class);
					String operatorType = map.get("operType");
					String bgmPath = map.get("path");


					// 2. 定义保存到本地的bgm路径
					String filePath = resourceConfig.getFileSpace() + bgmPath;
					log.info("1. ============ filePath:{}", filePath);
					// 3. 定义下载的路径（播放url）
//					String arrPath[] = songPath.split("/");			// linux
					String arrPath[] = bgmPath.split("\\\\");		// windows
					String finalPath = "";
					// 3.1 处理url的斜杠以及编码
					for(int i = 0; i < arrPath.length ; i ++) {
						if (StringUtils.isNotBlank(arrPath[i])) {
							finalPath += "/";
							finalPath += URLEncoder.encode(arrPath[i], "UTF-8") ;
						}
					}
					log.info("2. ============ finalPath:{}", finalPath);

					String bgmUrl = resourceConfig.getBgmServer() + finalPath;
					log.info("3. ============ bgmUrl:{}", bgmUrl);





					if (operatorType.equals(BGMOperatorType.ADD.type)) {
						// 下载bgm到spingboot服务器
						URL url = new URL(bgmUrl);
						File file = new File(filePath);
						FileUtils.copyURLToFile(url, file);
						client.delete().forPath(path);
					} else if (operatorType.equals(BGMOperatorType.DELETE.type)) {
						//spring端删除了bgm，boot端监听到之后也对bgm进行删除操作，并消耗掉节点
						File file = new File(filePath);
						FileUtils.forceDelete(file);
						client.delete().forPath(path);
					}
				}
			}
		});

	}

	
}
